<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 应用邀请码行为分析
 */

class AppInviteCodeBehavior extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'app_invite_code_behavior';

    /**
     * 记录浏览量
     * @param type  类型  与 getTypeName 方法对应
     * @return void
     */
    public function add($type_id = 1, $data = [])
    {
        if(empty(request()->invite_code_id)){
            return null;//不存在邀请码，就不添加
        }
        $this->user_id = isset(request()->user_info['id']) ? request()->user_info['id'] : 0;
        $this->type_id = $type_id;
        $this->invite_code_id = request()->invite_code_id;
        $this->save();
    }

    /**
     * 访问人数
     * @param invite_code_id string 邀请码id
     * @param type_id string 类型id
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     */
    public function getAccessNumber($invite_code_id, $type_id = null, $start_time = null, $end_time = null)
    {
        $number = $this->where(function ($query) use ($invite_code_id, $type_id, $start_time, $end_time) {
            if ($invite_code_id) {
                $query->where('invite_code_id', $invite_code_id);
            }
            if ($type_id) {
                $query->where('type_id', $type_id);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->count('id');
        return $number;
    }


    /**
     * 行为列表统计
     * @param page int 当前页
     * @param limit int 分页大小
     * @param start_time  开始时间
     * @param end_time  结束时间
     * @param invite_code_id string 邀请码id
     * @param type_id string 类型
     */
    public function lists($invite_code_id, $type_id = null,  $start_time = null, $end_time = null, $limit)
    {
        //  DB::enableQueryLog();
        $data = $this->from($this->getTable() . ' as b')
            ->select('b.id', 'w.nickname', 'w.head_img', 'c.name', 'b.type_id', 'b.create_time')
            ->join('app_invite_code as c', 'c.id', '=', 'b.invite_code_id')
            ->leftjoin('user_info as i', 'i.id', '=', 'b.user_id')
            ->leftjoin('user_wechat_info as w', 'w.id', '=', 'i.wechat_id')
            ->where(function ($query) use ($invite_code_id, $type_id, $start_time, $end_time) {
                if ($invite_code_id) {
                    $query->where('invite_code_id', $invite_code_id);
                }
                if ($type_id) {
                    $query->where('type_id', $type_id);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('b.create_time', [$start_time, $end_time]);
                }
            })
            ->orderByDesc('b.id')
            ->paginate($limit)
            ->toArray();
        //  dump(DB::getQueryLog());die;
        foreach ($data['data'] as $key => $val) {
            $data['data'][$key]['type_name'] = $this->getTypeName($val['type_id']);
        }

        return $data;
    }

    /**
     * 答题次数统计(折线图)
     * @param start_time  开始时间
     * @param end_time  结束时间
     * @param is_month  是否按月统计
     * @param invite_code_id string 邀请码id
     * @param type_id string 类型
     * @param node  方式  1 年  2 月   3 日  如果为空，则根据实际来
     */
    public function getAccessStatistics($invite_code_id, $type_id = null, $start_time = null, $end_time = null, $node = null)
    {
        if (empty($start_time)) {
            $start_time = date('Y-m-d 00:00:00');
            $end_time = date('Y-m-d H:i:s');
        }

        if ($node == 3 || (empty($node) && date('Y-m-d', strtotime($start_time)) == date('Y-m-d', strtotime($end_time)))) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d %H') as times"), DB::raw("count(id) as count")];
        } elseif ($node == 2 || (empty($node) && date('Y-m', strtotime($start_time)) == date('Y-m', strtotime($end_time)))) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d') as times"), DB::raw("count(id) as count")];
        } else {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m') as times"), DB::raw("count(id) as count")];
        }
        $res = $this->select($field)
            ->where(function ($query) use ($invite_code_id, $type_id, $start_time, $end_time) {
                if ($invite_code_id) {
                    $query->where('invite_code_id', $invite_code_id);
                }
                if ($type_id) {
                    $query->where('type_id', $type_id);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })
            ->orderBy('times')
            ->groupBy('times')
            ->get()
            ->toArray();
        return $res;
    }


    /**
     * 获取行为类型 
     * $type_id 行为类型   
     */
    public function getTypeName($type_id = null)
    {
        $data = [
            ['id' => 1, 'name' => '图书到家'],
            ['id' => 2, 'name' => '活动报名'],
            ['id' => 3, 'name' => '到馆预约'],
            ['id' => 4, 'name' => '座位预约'],
            ['id' => 5, 'name' => '空间预约'],
            ['id' => 6, 'name' => '师资预约'],
            ['id' => 7, 'name' => '设备预约'],
            ['id' => 8, 'name' => '教室预约'],
            ['id' => 9, 'name' => '展览预约'],
            ['id' => 10, 'name' => '数字悦读'],
            ['id' => 11, 'name' => '积分商城'],
            ['id' => 12, 'name' => '指尖办证'],
            ['id' => 13, 'name' => '馆藏检索'],
            ['id' => 14, 'name' => '读者荐购'],
            ['id' => 15, 'name' => '新闻动态'],
            ['id' => 16, 'name' => '新书推荐'],
            ['id' => 17, 'name' => '问卷调查'],
            ['id' => 18, 'name' => '阅读网点'],
            ['id' => 19, 'name' => '码上借'],
            ['id' => 20, 'name' => '文旅地图'],
            ['id' => 21, 'name' => '服务指南'],
            ['id' => 22, 'name' => '志愿者'],
            ['id' => 23, 'name' => '费用缴纳'],
            ['id' => 24, 'name' => '室内导航'],
            ['id' => 25, 'name' => '在线续借'],
            ['id' => 26, 'name' => '竞答'],
            ['id' => 27, 'name' => '抽奖'],
            ['id' => 28, 'name' => '投票'],
            ['id' => 29, 'name' => '直播'],
            ['id' => 30, 'name' => '首页'],
            ['id' => 31, 'name' => '储物柜预约'],
        ];
        if ($type_id) {
            $data = array_column($data, 'name', 'id');
            return $data[$type_id];
        }
        return $data;
    }
}
